import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:get/get.dart';
import 'package:jiffy/jiffy.dart';
import 'package:sgy_flutter/ble/ble_manager.dart';
import 'package:sgy_flutter/ble/custom_service.dart';
import 'package:sgy_flutter/ble/ext.dart';
import 'package:sgy_flutter/extensions/get.dart';
import 'package:sgy_flutter/gen/assets.gen.dart';
import 'package:sgy_flutter/model/abnormal_zero_record.dart';
import 'package:sgy_flutter/model/detection_result_model.dart';
import 'package:sgy_flutter/widget/fading_circle.dart';
import 'package:sgy_flutter/widget/sgy_scaffold.dart';
import 'package:dartx/dartx.dart';
import 'logic.dart';

class DetectionPage extends StatefulWidget {
  const DetectionPage({Key? key}) : super(key: key);

  @override
  State<DetectionPage> createState() => _DetectionPageState();
}

class _DetectionPageState extends State<DetectionPage> {
  final logic = Get.put(DetectionLogic());

  @override
  Widget build(BuildContext context) {
    return SgyScaffold(
        title: "设备诊断".tr,
        child: Obx(() => Container(
              width: double.infinity,
              height: double.infinity,
              child: switch (logic.state.value) {
                DetectionPageState.loading => _buildLoadingPage(),
                DetectionPageState.error => _buildErrorPage(),
                DetectionPageState.notSupport => _buildNotSupportPage(),
                DetectionPageState.success => _buildSuccessPage(),
              },
            )));
  }

  Widget _buildSuccessPage() {
    return SingleChildScrollView(
      child: Column(
        children: [
          Assets.image.iconSuccess.image(width: 100).marginOnly(top: 40),
          Text(
            "设备正常".tr,
            style: TextStyle(
                fontWeight: FontWeight.bold, fontSize: 18, color: Colors.black),
          ).marginOnly(top: 16),
          Obx(
            () => _buildInfo(
                deviceId: logic.bleManager.deviceModel?.deviceID,
                model: logic.resultModel.value,
                firmware: logic.firmware.value,
                record: logic.zeroRecord.value),
          ).marginOnly(top: 20),
          Visibility(
              visible: logic.resultModelRight.value != null,
              child: Obx(
                () => _buildInfo(
                    deviceId: logic.rightBleManager.deviceModel?.deviceID,
                    model: logic.resultModelRight.value,
                    firmware: logic.firmwareRight.value,
                    record: logic.zeroRecordRight.value),
              ).marginOnly(top: 20)),
          Visibility(
              visible: logic.resultModel.value?.result == true ||
                  logic.resultModel.value?.result == true,
              child: Text.rich(TextSpan(children: [
                WidgetSpan(
                    child: Assets.image.iconWarning
                        .image(width: 16, height: 16)
                        .marginOnly(top: 0, right: 4)),
                TextSpan(
                    text: "请凭此截图寻求售后。".tr,
                    style: TextStyle(
                        fontWeight: FontWeight.normal,
                        fontSize: 16,
                        color: Color(0xff888888))),
              ]))).marginOnly(top: 40, bottom: 40),
        ],
      ),
    );
  }

  Widget _buildInfo(
      {required DetectionResultModel? model,
      required String? firmware,
      required String? deviceId,
      required AbnormalZeroRecord? record}) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(left: 16, right: 16),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildItem("ID:", deviceId),
          _buildItem(model?.result == true ? "检测正常".tr : '检测异常'.tr, null),
          _buildItem("日期".tr + ":", "${logic.detectionDate}"),
          _buildItem("固件版本".tr + ":", "${firmware}").marginOnly(top: 12),
          _buildItem("电量检测值".tr + ":", "${model?.battery}"),
          _buildItem("比例数据".tr + ":", "${model?.ratio}"),
          _buildItem("高低温数据".tr + ":", "${model?.temperatureHex}"),
          _buildItem("零点数据".tr + ":", "${model?.zeroPoint}"),
          _buildItem("零点补偿".tr + ":", "${model?.zeroOffset}"),
          _buildItem("力矩数据".tr + ":",
              ":${model?.torqueList?.average().toStringAsFixed(0)}",
              red: model?.isTorqueNormal == false),
          _buildItem("传感器类型".tr + ":", "${model?.sensorType}"),
          _buildItem("传感器状态".tr + ":", "${model?.sensorState}",
              red: model?.sensorState != 0),
          _buildItem("传感器数据".tr + ":", "${model?.sensorDataHex}"),
          Visibility(
              visible: record != null && record.data.isNotEmpty == true,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  _buildItem("零点记录".tr + ":", ""),
                  ...(record?.data.mapIndexed((index, value) {
                        final dateTime = Jiffy.parseFromMillisecondsSinceEpoch(
                            record.date * 1000 * 60 + 1640966400000);
                        return _buildItem("${index + 1}:",
                            "$value   ${index == record.dateIndex ? "${dateTime.format(pattern: "yyyy-MM-dd HH:mm")}" : ""}");
                      }).toList() ??
                      [])
                ],
              ))
        ],
      ),
    );
  }

  Widget _buildItem(String label, String? value, {bool red = false}) {
    return Row(
      children: [
        Text(
          label,
          style: TextStyle(color: red ? Colors.red : null),
        ).marginOnly(right: 4),
        Text(
          value ?? "",
          style: TextStyle(color: red ? Colors.red : Colors.black87),
        ),
      ],
    ).marginOnly(top: 4);
  }

  Widget _buildLoadingPage() {
    return Column(
      children: [
        FadingCircle(
          color: Get.theme.primaryColor,
          size: 160,
        ),
        Text(
          "检测中".tr,
          style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 20,
              color: Color(0xff333333)),
        ).marginOnly(top: 40),
        Text.rich(TextSpan(children: [
          WidgetSpan(
              child: Assets.image.iconWarning
                  .image(width: 16, height: 16)
                  .marginOnly(top: 0, right: 4)),
          TextSpan(
              text: "请双脚离开踏板,确保功率计不受外力影响。请勿关闭手机屏幕或将应用切入后台。".tr,
              style: TextStyle(
                  fontWeight: FontWeight.normal,
                  fontSize: 15,
                  color: Color(0xff7a7a7a))),
        ])).marginOnly(top: 40),
      ],
    ).marginOnly(top: 20, left: 16, right: 16);
  }

  Widget _buildErrorPage() {
    return Container();
  }

  Widget _buildNotSupportPage() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Assets.image.iconWarningBlack.image(width: 60),
        Text.rich(TextSpan(children: [
          WidgetSpan(
              child: Assets.image.iconWarning
                  .image(width: 16, height: 16)
                  .marginOnly(top: 0, right: 4)),
          TextSpan(
              text: "设备不支持诊断,请先升级固件".tr,
              style: TextStyle(
                  fontWeight: FontWeight.normal,
                  fontSize: 15,
                  color: Color(0xff7a7a7a))),
        ])).marginOnly(top: 40),
      ],
    ).marginOnly(top: 20, left: 16, right: 16);
  }

  @override
  void dispose() {
    Get.delete<DetectionLogic>();
    super.dispose();
  }
}
